#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/4/1 10:28
# @Author : 闫峰
# @File    : api.py
import json
import time

import requests
from retrying import retry
from common.setting import ensure_path_sep
from third_services.aliexpress.utils import ErpDesUtil
# from other_project.aliexpress.model.aliexpress import ProductInfoListQuery,ProjectDetail
from utils.mysqlUtils.db_pool import Database


class AliexpressApi:

    def __init__(self, source_id):
        self.source_id = source_id

    @retry(stop_max_attempt_number=5, wait_fixed=2000)
    def product_list(self, current_page):
        """
        product_status_type
        商品业务状态，目前提供6种，输入参数分别是：
        上架:onSelling ；
        下架:offline ；
        审核中:auditing ；
        审核不通过:editingRequired；
        客服删除:service_delete ;
        所有删除商品：deleted；
        产品列表
        :return:
        """
        url = f"""https://erpapi.zhcxkj.com/Erp/AliExpressApi/PostProductRedefiningFindProductInfoListQuery"""
        header = {
            "Authorization": "Basic YXBpdXNlcjpFN0kxLWxJX2QjOGRscw=="
        }
        data = {
            "input": {
                "aeop_a_e_product_list_query": {
                    'current_page': current_page,
                    'excepted_product_ids': None,
                    'off_line_time': None,
                    'owner_member_id': None,
                    'page_size': 100,
                    'product_id': None,
                    'product_status_type': 'onSelling',
                    'subject': None,
                    'ws_display': None,
                    'have_national_quote': None,
                    'group_id': None,
                    'gmt_create_start': None,
                    'gmt_create_end': None,
                    'gmt_modified_start': "2024-01-01",
                    'gmt_modified_end': "2024-05-30"
                }

            },
            "UserTokenSecretAccessKey": ErpDesUtil.desEncode(AliexpressApi.get_user_token_secret_access_key(self.source_id))
        }
        res = requests.post(url, headers=header, json=data)
        # print(json.dumps(res.json(), indent=4))
        if res.status_code == 200:
            # print(json.dumps(res.json(), indent=4))
            return res.json()
        else:
            return Exception("status_code!=200")

    @staticmethod
    def get_user_token_secret_access_key(source_id):
        znkd_db = Database(ensure_path_sep("\\config\\znkd_mysql_config.yaml"), "znkd_database_prod")
        getOrderSourceIdUserTokenSecretAccessKey_list = """
        select b.UserTokenSecretAccessKey
        from sys_ordersource a
        left join sys_ordersource_authorization b on a.CustomerId=b.CustomerId and a.OrderSourceId=b.OrderSourceId
        where a.OrderSourceType=57
        and a.IsActive=1
        and a.IsDelete=0
        and a.CustomerId =1
        and b.IsActive=1
        and a.OrderSourceId = %s
        """
        OrderSourceIdUserTokenSecretAccessKey_list = znkd_db.fetch_all_tuple(
            getOrderSourceIdUserTokenSecretAccessKey_list, (source_id,))
        return OrderSourceIdUserTokenSecretAccessKey_list[0][0]

    @retry(stop_max_attempt_number=5, wait_fixed=2000)
    def get_product_detail(self, product_id):
        """
        POP 商品详情
        :return:
        """
        url = "https://erpapi.zhcxkj.com/Erp/AliExpressApi/OfferProductQuery"
        data = {
            "input": {
                "product_id": product_id
            },
            "UserTokenSecretAccessKey": ErpDesUtil.desEncode(AliexpressApi.get_user_token_secret_access_key(self.source_id))
        }
        header = {
            "Authorization": "Basic YXBpdXNlcjpFN0kxLWxJX2QjOGRscw=="
        }
        res = requests.post(url, headers=header,json=data)
        # print(json.dumps(res.json(), indent=4))
        return res.json()

    def PopChoiceProductQuery(self, product_id):
        """
        半托 商品详情
        :return:
        """
        url = "https://erpapi.zhcxkj.com/Erp/AliExpressApi/PopChoiceProductQuery"
        header = {
            "Authorization": "Basic YXBpdXNlcjpFN0kxLWxJX2QjOGRscw=="
        }
        data = {
            "input": {
                "product_id": product_id
            },
            "UserTokenSecretAccessKey": ErpDesUtil.desEncode(AliexpressApi.get_user_token_secret_access_key(self.source_id))
            # "UserTokenSecretAccessKey": "5FBC0F5E4F60AB21C04D7D6A2C62B44D9E65D111E47A2E9EEA0857EA511ACC3942B507E19C2366173BAA7FE4147E9831861401028AC0071052B26D2153F1123C0075AACF39803F96"
        }
        res = requests.post(url, headers=header, json=data)
        print(json.dumps(res.json(), indent=4))
        return res.json()

    # 获取商家账号列表
    def getMerchantProfileGet(self):
        url = "https://erpapi.zhcxkj.com/Erp/AliExpressApi/MerchantProfileGet"
        header = {
            "Authorization": "Basic YXBpdXNlcjpFN0kxLWxJX2QjOGRscw=="
        }
        data = {
                "input": {},
                "UserTokenSecretAccessKey": ErpDesUtil.desEncode(AliexpressApi.get_user_token_secret_access_key(self.source_id))
            }
        res = requests.post(url, headers=header, json=data)
        # print(json.dumps(res.json(), indent=4))
        return res.json()

    # 获取卖家资料
    def getGlobalSellerRelationQuery(self):
        url = "https://erpapi.zhcxkj.com/Erp/AliExpressApi/GlobalSellerRelationQuery"
        header = {
            "Authorization": "Basic YXBpdXNlcjpFN0kxLWxJX2QjOGRscw=="
        }
        data = {
                "input": {},
                "UserTokenSecretAccessKey": ErpDesUtil.desEncode(AliexpressApi.get_user_token_secret_access_key(self.source_id))
            }
        res = requests.post(url, headers=header, json=data)
        if res.status_code == 200:
            try:
                channel_seller_list = res.json().get('data').get('global_seller_relation_query_response',{}).get('seller_relation_list',{}).get('seller_relation')
                channel_seller_id = channel_seller_list[0].get('channel_seller_id')
                return channel_seller_id
            except Exception as e:
                raise Exception("请求异常")
        else:
            raise Exception("status_code!=200")

    def get_choice_products_list(self, product_status):
        """
        查询全托管店铺产品列表
        :param product_status:      ○ product_status：ONLINE 或 PENDING_LAUNCH
        :return:
        """
        url = "https://erpapi.zhcxkj.com/Erp/AliExpressApi/ChoiceProductsList"
        header = {
            "Authorization": "Basic YXBpdXNlcjpFN0kxLWxJX2QjOGRscw=="
        }
        data = {
                "input": {
                    "channel_seller_id": 2676768286,
                    "channel": "AE_GLOBAL",
                    "page_size": "20",
                    "current_page": 1,
                    "search_condition_do": {
                        "product_status": product_status
                    }
                },
                "UserTokenSecretAccessKey": ErpDesUtil.desEncode(AliexpressApi.get_user_token_secret_access_key(self.source_id))
            }

        res = requests.post(url, headers=header, json=data)
        print(json.dumps(res.json(), indent=4))
        return res.json()

    def PostProductRedefiningEditSingleSkuStock(self, product_id:int,sku_id:str,ipm_sku_stock:int):
        """
        编辑商品单个单体SKU库存
        :param product_status:
        :return:
        """
        url = "https://erpapi.zhcxkj.com/Erp/AliExpressApi/PostProductRedefiningEditSingleSkuStock"
        header = {
            "Authorization": "Basic YXBpdXNlcjpFN0kxLWxJX2QjOGRscw=="
        }
        data = {
            "input": {
                "product_id":product_id,
                "sku_id":sku_id,
                "ipm_sku_stock":ipm_sku_stock
            },
            "UserTokenSecretAccessKey": ErpDesUtil.desEncode(AliexpressApi.get_user_token_secret_access_key(self.source_id))
        }


        res = requests.post(url, headers=header, json=data)
        print(json.dumps(res.json(), indent=4))
        return res.json()

    def PostProductRedefiningEditMutilpleSkuStocks(self, product_id:int,sku_stocks):
        """
        编辑POP商品编多个SKU的库存
        :param product_status:
        :return:
        """
        url = "https://erpapi.zhcxkj.com/Erp/AliExpressApi/PostProductRedefiningEditMutilpleSkuStocks"
        header = {
            "Authorization": "Basic YXBpdXNlcjpFN0kxLWxJX2QjOGRscw=="
        }
        data = {
            "input": {
                "product_id": product_id,
                "sku_stocks": sku_stocks
            },
            "UserTokenSecretAccessKey": ErpDesUtil.desEncode(AliexpressApi.get_user_token_secret_access_key(self.source_id))
        }
        res = requests.post(url, headers=header, json=data)
        print(json.dumps(res.json(), indent=4))
        return res.json()

    def PopChoiceProductStocksUpdate(self):
        """
        编辑半托产品 可售数
        :param product_status:
        :return:
        """
        url = "https://erpapi.zhcxkj.com/Erp/AliExpressApi/PopChoiceProductStocksUpdate"
        header = {
            "Authorization": "Basic YXBpdXNlcjpFN0kxLWxJX2QjOGRscw=="
        }
        data = {
                "input": {
                             "pop_choice_sku_stock_list": [
                            {
                                "sku_id": "12000038835377588",
                                "pop_choice_sku_warehouse_stock_list": [
                            {
                                "sellable_quantity": 50,
                                "warehouse_code": "DGU002-JIT"
                            },
                            {
                                "sellable_quantity": 0,
                                "warehouse_code": "HZU002-JIT"
                            }
                    ]
                }
            ],
            "product_id": 1005006951271307
        },
            "UserTokenSecretAccessKey": ErpDesUtil.desEncode(AliexpressApi.get_user_token_secret_access_key(self.source_id))
        }
        res = requests.post(url, headers=header, json=data)
        print(json.dumps(res.json(), indent=4))
        return res.json()

        # 查询半托管待加入商品列表 接口

    def PopChoiceProductsList(self, current_page,):
        url = f"""https://erpapi.zhcxkj.com/Erp/AliExpressApi/PopChoiceProductsList"""
        headers = {
            "Authorization": "Basic YXBpdXNlcjpFN0kxLWxJX2QjOGRscw=="
        }
        data = {
            "input": {
                "param": {
                    "joined_product_tab": "selected",
                    "current_page": current_page,
                    "page_size": 50
                }
            },
            "UserTokenSecretAccessKey": ErpDesUtil.desEncode(AliexpressApi.get_user_token_secret_access_key(self.source_id))
        }

        for attempt in range(10):
            try:
                resp = requests.post(url=url, headers=headers, json=data)
                if resp.status_code == 200:
                    pop_choice_product = resp.json()
                    if 'data' in pop_choice_product and pop_choice_product['data']['aliexpress_pop_choice_products_list_response']["result"]:
                        return pop_choice_product
                        # 可以在这里选择直接抛出异常，或者继续重试（如果尚未达到最大重试次数）
                    else:
                        print(f"data 不在返回的参数中,将尝试重新获取...")
            except requests.RequestException as e:
                print(f"请求失败：{e}，将尝试重新获取...")
                # 在请求失败时也需要等待一段时间再重试
                time.sleep(1)
        raise Exception("达到最大重试次数，未能成功获取数据")

    def PopChoiceDraftQueryRequest(self, product_id: int):
        """
        商品可升级为半托管SKU信息查询
        """
        # print(f"source_id={source_id} current_page={current_page}")
        url = f"""https://erpapi.zhcxkj.com/Erp/AliExpressApi/PopChoiceDraftQueryRequest"""
        headers = {
            "Authorization": "Basic YXBpdXNlcjpFN0kxLWxJX2QjOGRscw=="
        }
        data = {
                    "input": {
                "product_id": product_id
            },
            "UserTokenSecretAccessKey": ErpDesUtil.desEncode(AliexpressApi.get_user_token_secret_access_key(self.source_id))
        }
        res = requests.post(url=url, headers=headers, json=data)
        if res.status_code == 200:
            """
                       {
                'product_status': 'onSelling',
                'modified_time': '2024-06-11 01:12:27',
                'product_image': 'https://ae01.alicdn.com/kf/S1c99398fd85b4bb5be5cba12ac6165e2O.jpg',
                'product_id': 1005007151151172,
                'create_time': '2024-06-08 05:11:06',
                'total_stocks': 'null',
                'max_sku_price': '6.72',
                'min_sku_price': '5.85',
                'title': 'Probe Turkey Roasting Rack Digital Thermometer Baby Food Barbecue Canning Jar Lids',
                'currency_code': 'USD'
            }
            """

            try:
                total_page = res.json()['data']['aliexpress_pop_choice_products_list_response']["result"]['total_page']
                pop_choice_product = \
                    res.json()['data']['aliexpress_pop_choice_products_list_response']["result"][
                        'pop_choice_product_list']['pop_choice_product']
            except Exception as e:
                raise Exception(f"source_id={self.source_id}  请求异常")

            return total_page, pop_choice_product
        else:
            raise Exception("status_code!=200")

    # 获取半托管目前支持的国家列表 country_list
    def PopChoiceInfoQuery(self):
        """
        商家半托管基本信息查询接口
        """
        # print(f"source_id={source_id} current_page={current_page}")
        url = f"""https://erpapi.zhcxkj.com/Erp/AliExpressApi/PopChoiceInfoQuery"""
        headers = {
            "Authorization": "Basic YXBpdXNlcjpFN0kxLWxJX2QjOGRscw=="
        }
        data = {
                    "input": None,
            "UserTokenSecretAccessKey": ErpDesUtil.desEncode(AliexpressApi.get_user_token_secret_access_key(self.source_id))
        }
        res = requests.post(url=url, headers=headers, json=data)
        if res.status_code == 200:
            """
                       {
                'product_status': 'onSelling',
                'modified_time': '2024-06-11 01:12:27',
                'product_image': 'https://ae01.alicdn.com/kf/S1c99398fd85b4bb5be5cba12ac6165e2O.jpg',
                'product_id': 1005007151151172,
                'create_time': '2024-06-08 05:11:06',
                'total_stocks': 'null',
                'max_sku_price': '6.72',
                'min_sku_price': '5.85',
                'title': 'Probe Turkey Roasting Rack Digital Thermometer Baby Food Barbecue Canning Jar Lids',
                'currency_code': 'USD'
            }
            """

            try:
                country_code_list = res.json()['data']['aliexpress_pop_choice_info_query_response']["result"]\
                    ['pop_choice_country_list']['pop_choice_country']
                country_list = list(map(lambda country: country['country_code'], country_code_list))
                print(country_list)
            except Exception as e:
                raise Exception(f"source_id={self.source_id}请求异常")

            return country_list
        else:
            raise Exception("status_code!=200")

    def FreightRedefiningListFreightTemplate(self):
        url = f"""https://erpapi.zhcxkj.com/Erp/AliExpressApi/FreightRedefiningListFreightTemplate"""
        headers = {
            "Authorization": "Basic YXBpdXNlcjpFN0kxLWxJX2QjOGRscw=="
        }
        data = {
                        "input": {
                                    "orderSourceId": 5208
                },
            "UserTokenSecretAccessKey": ErpDesUtil.desEncode(AliexpressApi.get_user_token_secret_access_key(self.source_id))
        }
        res = requests.post(url=url, headers=headers, json=data)
        if res.status_code == 200:
            if res.json().get('data').get('aliexpress_freight_redefining_listfreighttemplate_response').get('result_success'):

                try:
                    aeopfreighttemplatedto_list = res.json().get('data').get('aliexpress_freight_redefining_listfreighttemplate_response').get('aeop_freight_template_d_t_o_list').get('aeopfreighttemplatedtolist')
                    return aeopfreighttemplatedto_list
                except Exception as e:
                    raise Exception(f"source_id={self.source_id}FreightRedefiningListFreightTemplate请求异常")

            else:
                raise Exception("result_success!=true")
        else:
            raise Exception("status_code!=200")

    # 获取营销图
    def getproductmarketingimages(self):
        url = f"""https://erpapi.zhcxkj.com/erp/products/getproductmarketingimages"""
        headers = {
            "Authorization": "Basic YXBpdXNlcjpFN0kxLWxJX2QjOGRscw=="
        }
        data = {
                    "input":{"customerId":1,"startTime":"2024-05-21 17:00:00","endTime":"2024-05-29 19:00:00","pageIndex":1,"pageSize":1000}
                }
        res = requests.post(url=url, headers=headers, json=data)
        if res.status_code == 200:
            if res.json().get('status'):
                try:
                    product_marketing_images_list = res.json().get('data').get('list')
                    return product_marketing_images_list,
                except Exception as e:
                    raise Exception(f"source_id={self.source_id}getproductmarketingimages请求异常")

            else:
                raise Exception("result_success!=true")
        else:
            raise Exception("status_code!=200")

    # 全托管店铺-查询单个商品详情
    def ChoiceProductQuery(self):
        """
        20484	50000900b23grXjAp4QUADdfTGoxewujadg1d8bdbb7w7tS1jhEwh1fsx4I0Ta31YY2	2677850022
        20463	50000600a15NeH8iBsvqxgc2ITe19d67023pweyPhWCcxAlrYChlPJzkxcZe2u3Fp3v	2676768286
        22045	50000200101cw18e41f36zxTpDfqMdvilkoYuuhbbGUEIvcuPD8bCtBOvdaBQ8iNsaz	2678856002
        22077	50000401903fiGb1943a616sqfdBiuBOxuekfPmxhu0BCbEuQhSwxyspY7TQKWd78SN	2680418434
        22311	50000501824wd8ratOjfECv3LT1dgfNk3Fvt1ff6bb42Hh5GSrBKx1PnuLuqVFO2udp	2679840215
        22312	50000201928fiGbsqEejFP3ow1djgymaDq1BhwGt1f23868aOdvTxqppX2TtNui78SN	2680369232
        """
        url = "https://erpapi.zhcxkj.com/Erp/AliExpressApi/ChoiceProductQuery"
        header = {
            "Authorization": "Basic YXBpdXNlcjpFN0kxLWxJX2QjOGRscw=="
        }
        data = {
                "input": {
                            "channel_seller_id": 2676768286,
                            "channel": "AE_GLOBAL",
                            "product_id": 1005006499771009
                        },
                "UserTokenSecretAccessKey": ErpDesUtil.desEncode(AliexpressApi.get_user_token_secret_access_key(self.source_id))
            }
        res = requests.post(url, headers=header, json=data)
        print(json.dumps(res.json(), indent=4))
        return res.json()

    # 根据发布类目id、父属性路径（可选）获取子属性信息，只返回有权限品牌
    def CategoryRedefiningGetChildAttributes(self,category_id):
        url = f"""https://erpapi.zhcxkj.com/Erp/AliExpressApi/CategoryRedefiningGetChildAttributesResultByPostCateidAndPath"""
        headers = {
            "Authorization": "Basic YXBpdXNlcjpFN0kxLWxJX2QjOGRscw=="
        }
        data = {
                "input": {
                  "param1": category_id,
                },
                "UserTokenSecretAccessKey": ErpDesUtil.desEncode(AliexpressApi.get_user_token_secret_access_key(self.source_id))
            }
        res = requests.post(url=url, headers=headers, json=data)
        if res.status_code == 200:
            try:
                # 一次性解析 JSON 数据
                data = res.json()
                # 尝试获取 'result' 部分
                rsp_result = data.get('data', {}).get(
                    'aliexpress_category_redefining_getchildattributesresultbypostcateidandpath_response', {}).get(
                    'result')
                # 检查 'error_message'
                error_message = rsp_result.get('error_message')
                if error_message:
                    # 如果存在错误消息，则处理错误（这里只是打印，您可以根据需要修改）
                    print(f"Error: {error_message}")
                    # 可能需要返回一个错误响应或抛出异常
                    # return None, 或者 raise SomeError("Error message")
                else:
                    # 如果没有错误，尝试获取 'brand_attribute'
                    brand_attributes = rsp_result.get('attributes', {}).get('aeop_attribute_dto', {})
                    # 返回 brand_attributes
                    return brand_attributes
            except Exception as e:
                # 捕获任何在解析或访问数据时发生的异常
                raise Exception(f"source_id={self.source_id} CategoryRedefiningGetChildAttributes请求异常: {e}")
        else:
            # 如果状态码不是 200，则处理非成功响应（这里只是打印，您可以根据需要修改）
            print(f"请求失败，状态码：{res.status_code}")

    # 根据 source id 获取 可刊登一级分类
    def CategoryTreeList(self,channel_seller_id,category_id):
        url = f"""https://erpapi.zhcxkj.com/Erp/AliExpressApi/CategoryTreeList"""
        headers = {
            "Authorization": "Basic YXBpdXNlcjpFN0kxLWxJX2QjOGRscw=="
        }
        data = {
                "input": {
                 "channel_seller_id": channel_seller_id,
                 "only_with_permission": True,
                 "channel": "AE_GLOBAL",
                 "category_id": category_id
                },
                "UserTokenSecretAccessKey":ErpDesUtil.desEncode(AliexpressApi.get_user_token_secret_access_key(
                    self.source_id))
        }
        res = requests.post(url=url, headers=headers, json=data)
        if res.status_code == 200 and res.json().get('data'):
            # 如果没有错误，尝试获取 'brand_attribute'
            level1_category_list = res.json().get('data').get('aliexpress_category_tree_list_response', {}).get('aeop_post_category_list', {}).get('aeop_post_category', [])
            # 返回 level1_category_list
            return level1_category_list
        else:
            print(f"请求失败，Error processing category ID: {category_id}")
            return False

    # 根据 类目 id 获取子类目
    def CategoryRedefiningGetChildrenPostCategoryById(self,category_id):
        url = f"""https://erpapi.zhcxkj.com/Erp/AliExpressApi/CategoryRedefiningGetChildrenPostCategoryById"""
        headers = {
            "Authorization": "Basic YXBpdXNlcjpFN0kxLWxJX2QjOGRscw=="
        }
        data = {
                "input": {
                    "param0": f"{category_id}"  # 发布类目ID
                },
                "UserTokenSecretAccessKey":ErpDesUtil.desEncode(AliexpressApi.get_user_token_secret_access_key(self.source_id))
        }
        res = requests.post(url=url, headers=headers, json=data)
        if res.status_code == 200:
            if res.json().get('data'):
                # 如果没有错误，尝试获取 'children_list'
                children_list = res.json().get('data').get('aliexpress_category_redefining_getchildrenpostcategorybyid_response',{}).get('result', {}).get('aeop_post_category_list', {}).get('aeop_post_category_dto', [])
                return children_list
            else:
                return False
        else:
            # 如果状态码不是 200，则处理非成功响应（这里只是打印，您可以根据需要修改）
            print(f"请求失败，状态码：{res.status_code}")

    # 获取 系统销量
    def get_sales_summary(self,index,start_time,end_time):
        url = f"""http://erpapi.zhcxkj.com/erp/products/GetOrderSourceDaySalesSummary"""
        headers = {
            "Authorization": "Basic YXBpdXNlcjpFN0kxLWxJX2QjOGRscw=="
        }
        data ={
                "current": index,
                "pageSize": 500,
                "orderBy": {
                    "field": "orderSourceId",
                    "order": 0
                },
                "input": {
                    "customerId": 1,
                    "OrderSourceType": 57,
                    "StartTime": start_time,
                    "EndTime": end_time
                    }
        }
        resp = requests.post(url=url, headers=headers, json=data)
        if resp.status_code == 200:
            if resp.json().get('data'):
                # 如果没有错误，尝试获取 'children_list'
                sales_summary_data = resp.json().get('data')
                return sales_summary_data
            else:
                return False
        else:
            # 如果状态码不是 200，则处理非成功响应（这里只是打印，您可以根据需要修改）
            print(f"请求失败，状态码：{resp.status_code}")

    # 获取 商品诊断
    def get_product_problem(self,index):
        url = f"""http://erpapi.zhcxkj.com/Erp/AliExpressApi/AliExpressProductDiagnosisPageQueryProblem"""
        headers = {
            "Authorization": "Basic YXBpdXNlcjpFN0kxLWxJX2QjOGRscw=="
        }
        data = {
            "input": {
                "UserTokenSecretAccessKey": ErpDesUtil.desEncode(AliexpressApi.get_user_token_secret_access_key(self.source_id)),
                "operate_status": 0
            },
            "Current": index,
            "PageSize": 30
        }

        for attempt in range(10):
            try:
                resp = requests.post(url=url, headers=headers, json=data)
                if resp.status_code == 200:
                    product_problem_data = resp.json()
                    if 'data' in product_problem_data:
                        return product_problem_data
                    else:
                        print("响应中包含的数据缺失'data'键，将尝试重新获取...")
                        # 可以在这里选择直接抛出异常，或者继续重试（如果尚未达到最大重试次数）
            except requests.RequestException as e:
                print(f"请求失败：{e}，将尝试重新获取...")
                # 在请求失败时也需要等待一段时间再重试
                time.sleep(1)
        raise Exception("达到最大重试次数，未能成功获取数据")

    # 获取 全托管商品 列表数据 2679840215-22311,
    def get_choice_product_list(self,channel_seller_id,index,status:str):
        url = f"""http://erpapi.zhcxkj.com/Erp/AliExpressApi/ChoiceProductsList"""
        headers = {
            "Authorization": "Basic YXBpdXNlcjpFN0kxLWxJX2QjOGRscw=="
        }
        data ={
                "input": {
                    "channel_seller_id": channel_seller_id,
                    "channel": "AE_GLOBAL",
                    "page_size": "20",
                    "current_page": index,
                    "search_condition_do": {
                        "product_status": status,
                    }
                },
                "UserTokenSecretAccessKey": ErpDesUtil.desEncode(AliexpressApi.get_user_token_secret_access_key(self.source_id))
            }
        for attempt in range(5):
            try:
                resp = requests.post(url=url, headers=headers, json=data)
                if resp.status_code == 200:
                    resp_data = resp.json()
                    if 'data' in resp_data and resp_data.get('data').get('aliexpress_choice_products_list_response'):
                        choice_product_data = resp.json().get('data').get('aliexpress_choice_products_list_response')
                        return choice_product_data
                    else:
                        print("响应中包含的数据缺失'data'键，将尝试重新获取...")
                        # 可以在这里选择直接抛出异常，或者继续重试（如果尚未达到最大重试次数）
            except requests.RequestException as e:
                print(f"请求失败：{e}，将尝试重新获取...")
                # 在请求失败时也需要等待一段时间再重试
        raise Exception("达到最大重试次数，未能成功获取数据")

    # 获取 刊登额度


if __name__ == '__main__':
    # res = AliexpressApi(5204).get_product_problem(1)
    # Api(5242).product_list(1)
    # res = AliexpressApi(5212).CategoryTreeList(226911366)
    # res = AliexpressApi(5212).CategoryRedefiningGetChildrenPostCategoryById(13)
    # res= AliexpressApi(5212).getGlobalSellerRelationQuery()
    # res = AliexpressApi(5212).CategoryRedefiningGetChildAttributes(100004470)
    # data = Api(5242).product_list(1).get('data').get('aliexpress_postproduct_redefining_findproductinfolistquery_response').get('result')
    # r = ProductInfoListQuery(**data)
    # print(r.dict())
    # res = Api(5242).product_list(11)
    # product_id = 32798989398
    # sku_id = '14:1052'
    # ipm_sku_stock = 934
    # res = Api(5159).PostProductRedefiningEditSingleSkuStock(product_id,sku_id,ipm_sku_stock)
    # sku_stocks = {'14:771':426,'14:193':50}
    # res = Api(5212).PopChoiceDraftQueryRequest(1005007151151172)
    # res = Api(5212).PostProductRedefiningEditMutilpleSkuStocks(product_id,sku_stocks)
    # res = AliexpressApi(20463).ChoiceProductQuery()
    # res = AliexpressApi(23037).get_product_detail(8541651917)
    # res = AliexpressApi(5204).PopChoiceProductQuery(1005006851467761)
    # res = AliexpressApi(10010).PopChoiceProductQuery(1005006878250520)
    # res = AliexpressApi(5204).PopChoiceProductsList(11111)
    # res = AliexpressApi(20666).get_product_detail(1005007201543075)
    # res = AliexpressApi(22312).ChoiceProductQuery()
    # res = Api(5212).PopChoiceInfoQuery()
    # res = AliexpressApi(5208).FreightRedefiningListFreightTemplate()
    # ErpDesUtil.desEncode(AliexpressApi.get_user_token_secret_access_key(11354))
    # res = AliexpressApi(20463).get_choice_products_list("PENDING_LAUNCH")
    # res = AliexpressApi(22312).get_choice_products_list("PENDING_LAUNCH")
    # res = Api(20484).product_list(1)
    # res = Api(5212).get_pop_product_detail(1005007151151172)
    # res = Api(5212).getPopChoiceInfoQuery()
    # res = res.get('data').get('aliexpress_pop_choice_product_query_response').get('result').get('pop_choice_product')
    # r = PopDetail(**res)
    # print()
    # Api(5242).get_pop_product_detail(1005006769201607)
    res = AliexpressApi(22311).get_choice_product_list(1)
